package com.iussoft.receiveData.send.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import com.iussoft.analyze.impl.SuperDataManager;
import com.iussoft.model.DataParams;
import com.iussoft.mysql.ReqParamVo;
import com.iussoft.receiveData.kafka.KafkaSimpleSender;
import com.iussoft.receiveData.redis.EsManager;
import com.iussoft.receiveData.schedul.ScheduledDynamicTask;
import com.iussoft.tools.JedisPoolFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * @description:
 * @author: Hou Dayu
 * @date: Created in 2020/3/18
 */
public abstract class SuperSearchManager extends SuperDataManager {

    @Autowired
    @Qualifier("esManager")
    protected EsManager esManager;
    @Autowired
    @Qualifier("scheduledDynamicTask")
    private ScheduledDynamicTask dynamicTask;
    @Autowired
    protected KafkaSimpleSender kafkaSimpleSender;
    @Autowired
    protected DepositCertificateManager depositCertificateManager;
    private static final String INTER_RELATION_KEY="dxpInterfaceRelation";//接口关系缓存KEY

    protected final String indexName = "depositcertificate";//存证ES索引
    protected final String analyzeIndexName = "dataanalyze";//存储ES索引

    public String getConfig(String key) {//data.sync.enabled
        return env.getProperty(StrUtil.doNull(key,"data.sync.enabled"));//默认获取是否开启数据同步配置属性
    }

    public String getHbaseTableName(int type){
        switch (type){
            case 1:
                return env.getProperty("hbase.tableName");//存证hbase表名
            case 2:
                return env.getProperty("hbase.analyze.tableName");//存储hbase表名
            default:
                return "deaultMessage";
        }
    }

    public String sendMsgTopic(int type){
        switch (type){
            case 1:
                return env.getProperty("kafka.receive.topic");//接收消息topic
            case 2:
                return env.getProperty("kafka.send.async.topic");//发送消息异步topic
            default:
                return env.getProperty("kafka.send.alldata.topic");//发送消息到数据写入服务topic
        }
    }

    /**
     * 配置规则
     */
    protected DataMap<String> getRuleSite(String infoId){
        ReqParamVo vo = new ReqParamVo();
        vo.setWheres("interfaceId",infoId);
        vo.setTableName("dx_gw_rule_site");
        DataMap info = unifiedDataDao.selectById(vo);
        if(null == info){
            info = new DataMap();
        }
        return info;
    }

    public JSONObject getDxSysIntRelation(String requestCode){
        String data = String.valueOf(redisManager.getObjCache(INTER_RELATION_KEY,requestCode, JedisPoolFactory.DATABASE));
        if (StrUtil.isNull(data)) {
            ReqParamVo vo = new ReqParamVo();
            vo.setWheres("requestCode",requestCode);
            vo.setTableName("dx_sys_int_relation");
            DataMap<String> map = unifiedDataDao.selectById(vo);
            if(map == null || map.isEmpty()){
                //关系表获取不取直接从服务注册表获取
                vo = new ReqParamVo();
                vo.setWheres("interfaceCode",requestCode);
                vo.setTableName("dx_interface_reg");
                DataMap<String> imap = unifiedDataDao.selectById(vo);
                if (null != imap) {
                    JSONObject json = new JSONObject();
                    json.put("fromInterfaceCode",imap.get("interfaceCode"));
                    json.put("fromServerId",imap.get("infoId"));
                    json.put("requestCode",imap.get("interfaceCode"));
                    json.put("requestPwd","");
                    json.put("exchangeMode",imap.get("exchangeMode"));
                    json.put("sysEname",imap.get("sysEname"));
                    return json;
                }
                return null;
            }
            JSONObject json = new JSONObject();
            json.put("fromInterfaceCode",map.get("fromInterfaceCode"));
            json.put("fromServerId",map.get("fromServerId"));
            json.put("requestCode",map.get("requestCode"));
            json.put("requestPwd",map.get("requestPwd"));
            json.put("exchangeMode",map.get("exchangeMode"));
            json.put("sysEname",map.get("sysEname"));
            redisManager.createObjCache(INTER_RELATION_KEY,requestCode,json.toJSONString(),0, JedisPoolFactory.DATABASE);
            return json;
        }else{
            return JSON.parseObject(data);
        }
    }

    /**
     * 获取接口参数信息
     *//*
    protected Map<String, Object> getInterfaceParams(String serverId,String formatType){
        long startTime = System.currentTimeMillis();
        ReqParamVo param = new ReqParamVo();
        param.setTableName("dx_msg_format_set");
        param.setWheres("interfaceId",serverId);
        param.setWheresIn("msgType",StrUtil.doNull(formatType,"'resp'"));//报文格式类型(req,resp)
        param.setOrderStr(" param_parent ,param_ename");
        List<DataMap> list = unifiedDataDao.select(param);
        if(StrUtil.isEmpty(list)){
            return new HashMap<>();
        }
        Map<String, Object> bodyMap = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        Map<String, Object> urlMap = new HashMap<>();
        Map<String, Object> MenuList = new HashMap<>();
        int count = 0;
        Map<String,List<String>> group = getGroupNode(list);
        for(DataMap<String> vo: list){
            int num = 0;
            Map<String,Object> map = new HashMap<String,Object>();
            if("0".equals(vo.get("paramParent"))){//通过判断，0代表没有父级，也就是一级
                String paramEame = vo.get("paramEname");
                if("header".equals(vo.get("msgType")) || "params".equals(vo.get("msgType"))){
                    if("defaultRoot".equals(paramEame)){
                        Map<String, Object> data = getChildren(list, vo.get("infoId"), paramEame, vo.get("msgType"), group);
                        if (data != null) {
                            data.remove("nodecount");
                            if("header".equals(vo.get("msgType"))) {
                                headerMap.putAll(data);
                            }else{
                                urlMap.putAll(data);
                            }
                        }
                    }else {
                        if ("header".equals(vo.get("msgType"))) {
                            headerMap.put(paramEame, StrUtil.doNull(vo.get("defValue"), ""));
                        } else {
                            urlMap.put(paramEame, StrUtil.doNull(vo.get("defValue"), ""));
                        }
                    }
                } else {
                    map.put("paramEname",paramEame);
                    map.put("cloumEname",vo.get("cloumEname"));
                    map.put("ifNull",vo.get("ifNull"));
                    map.put("paramType",vo.get("paramType"));
                    map.put("ifUse",vo.get("ifUse"));
                    map.put("ifRowKey",vo.get("ifRowKey"));
                    if("1".equals(vo.get("ifSubParam"))) {
                        Map<String,Object> data = getChildren(list, vo.get("infoId"),paramEame,vo.get("msgType"), group);
                        if(data != null) {
                            map.put("children", data);//继续往一级下面遍历，调用下面的处理方法，放入树状结构
                            if(data != null){
                                int cdNum = Integer.parseInt(String.valueOf(data.get("nodecount")));
                                count = count + cdNum;
                                num += cdNum;
                            }
                            if("defaultRoot".equals(paramEame) && "json".equals(vo.get("interfaceRMFT"))){
                                bodyMap.putAll(data);
                            }
                        }
                    }
                    if("defaultRoot".equals(paramEame) && "json".equals(vo.get("interfaceRMFT"))){
                    } else {
                        num += 1;
                        map.put("nodecount",num);
                        bodyMap.put(paramEame, map);//先把一级存入结果
                    }
                }
            }
        }
        bodyMap.put("nodecount",count);
        MenuList.put("body",bodyMap);
        MenuList.put("header",headerMap);
        MenuList.put("params",urlMap);
        LoggerUtil.info("getInterfaceParams方法执行时间："+(System.currentTimeMillis()-startTime)+" ms");
        return MenuList;
    }

    //结果集转树状结构
    private Map<String, Object> getChildren(List<DataMap> data,String menuId,String parentEname,String msgType,Map<String,List<String>> group){//参数为数据库的（原数据，一级id）
        if(data==null || data.size()==0 || StrUtil.isNull(menuId)){
            return null;
        }
        Map<String, Object> menuList = new HashMap<>();
        int count = 0;
        for(DataMap<String> vo : data){
            if("F".equals(vo.get("flag"))){
                continue;
            }
            int num = 0;
            if(menuId.equals(vo.get("paramParent")) && msgType.equals(vo.get("msgType"))){//如果本级id与下面数据的父id相同，就说明是子父级关系
                String paramEame = vo.get("paramEname");
                if("header".equals(vo.get("msgType")) || "params".equals(vo.get("msgType"))){
                    if("header".equals(vo.get("msgType"))) {
                        menuList.put(paramEame, StrUtil.doNull(vo.get("defValue"), ""));
                    } else {
                        menuList.put(paramEame, StrUtil.doNull(vo.get("defValue"), ""));
                    }
                    vo.put("flag","F");
                } else {
                    List<String> nodes = group.get(vo.get("paramParent"));
                    List<String> sameNodes = getSameNode(nodes,paramEame);
                    List<Map> nodeList = new ArrayList();
                    for(String node : sameNodes){
                        String str[] = node.split(";");
                        DataMap<String> dm = data.get(Integer.parseInt(str[1]));
                        Map<String,Object> map = new HashMap();
                        map.put("paramEname",str[0]);
                        map.put("cloumEname",dm.get("cloumEname"));
                        map.put("ifNull",dm.get("ifNull"));
                        map.put("paramType",dm.get("paramType"));
                        map.put("ifUse",vo.get("ifUse"));
                        map.put("ifRowKey",vo.get("ifRowKey"));
                        dm.put("flag","F");
                        if("1".equals(dm.get("ifSubParam"))) {
                            Map<String,Object> children = getChildren(data, dm.get("infoId"),str[0],dm.get("msgType"),group);
                            if(children != null){
                                map.put("children",children);
                                int cdNum = Integer.parseInt(StrUtil.doNull(String.valueOf(children.get("nodecount")),"0"));
                                count = count + cdNum;
                                num += cdNum;
                            } else {
                                num +=1;
                                count = count +1;
                            }
                        } else {
                            num +=1;
                            count = count +1;
                        }
                        map.put("nodecount",num);
                        nodeList.add(map);
                    }
                    if(nodeList.size()==1){
                        menuList.put(paramEame, nodeList.get(0));
                    } else if(nodeList.size()>1) {
                        menuList.put(parentEname, nodeList);
                    }
                }
            }
        }
        menuList.put("nodecount",count);
        return menuList;
    }

    private Map<String,List<String>> getGroupNode(List<DataMap> data){
        Map<String,List<String>> mapData = new HashMap();
        for(int i=0; i<data.size();i++){
            DataMap<String> vo = data.get(i);
            String pid = vo.get("paramParent");
            if("0".equals(pid)){
                continue;
            }
            List<String> list = mapData.get(pid);
            if(null == list){
                list = new ArrayList();
            }
            list.add(vo.get("paramEname")+";"+i);
            mapData.put(pid,list);
        }
        return mapData;
    }

    private List<String> getSameNode(List<String> data,String nodeName){
        List<String> list = new ArrayList();
        for(String vo : data){
            if(vo.startsWith(nodeName+";")){
                list.add(vo);
            }
        }
        return list;
    }*/

    public String rollbackStr(String str){
        StringBuilder resultString = new StringBuilder();
        char[] charArray = str.toCharArray();
        for (int i = charArray.length - 1; i >= 0; i--) {
            resultString.append(charArray[i]);
        }
        return resultString.toString();
    }

    public void depositCertificate(final DataParams params,final int type){//处理信息存证

        dynamicTask.submit(new Runnable() {
            DataParams dps = new DataParams();
            public void run() {
                try {
                    dps.setTraceId(params.getTraceId());
                    dps.setParams(params.getParams());
                    switch (type) {
                        case 1:
                            depositCertificateManager.sendDataMsg(dps);
                            break;
                        case 2:
                            depositCertificateManager.syncSendData(dps);
                            break;
                        case 3:
                            depositCertificateManager.receiveDataMsg(dps);
                            break;
                        case 4:
                            depositCertificateManager.asyncSendData(dps);
                    }
                }catch (Exception e){

                }
            }
        });
    }
}
